package com.loong.musicdemo.util.dataDeal;

import android.util.Log;

import com.loong.musicdemo.model.Album;
import com.loong.musicdemo.util.httpUtil.HttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class AlbumDeal {

    /**
     * 获取新专辑内容
     * @return 专辑集合
     */
    public static List<Album> getNewestAlbumInfo(){
        String url = "http://47.112.224.146:3000/album/newest";
        String response = HttpUtil.sendReturnOKHttpRequest(url);
        List<Album> albumList = new ArrayList<>();
        try {
            JSONObject object = new JSONObject(response);
            JSONArray albums = object.getJSONArray("albums");
            for(int i = 0;i<albums.length();i++){
                JSONObject a = albums.getJSONObject(i);
                Album album = new Album();
                JSONObject artist = a.getJSONObject("artist");
                album.setAlbumId(a.getString("id"));
                album.setAlbumName(a.getString("name"));
                album.setAlbumPicUrl(a.getString("picUrl"));
                album.setAlbumArtistId(artist.getString("id"));
                album.setAlbumArtistName(artist.getString("name"));
                album.setAlbumArtistPicUrl(artist.getString("picUrl"));
                album.setSongIdsInAlbum(getSongIdOfAlbum(album.getAlbumId()));
                album.setAlbumCommentCount(getAlbumCommentCount(album.getAlbumId()));
                albumList.add(album);
            }
            Log.i("sjdks",albumList.size()+"");
            return albumList;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取专辑中的歌曲id
     * @param id 专辑id
     * @return 歌曲id结合
     */
    public static List<String> getSongIdOfAlbum(String id){
        String url = "http://47.112.224.146:3000/album?id="+id;
        String response = HttpUtil.sendReturnOKHttpRequest(url);
        List<String> songIds = new ArrayList<>();
        try {
            JSONObject object = new JSONObject(response);
            JSONArray songs = object.getJSONArray("songs");
            for(int i = 0;i<songs.length();i++){
                JSONObject song = songs.getJSONObject(i);
                songIds.add(song.getString("id"));
            }
            return songIds;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取专辑的评论数
     * @param albumId 专辑id
     * @return  评论数
     */
    public static String getAlbumCommentCount(String albumId){
        String url = "http://47.112.224.146:3000/comment/album?id="+albumId;
        String response = HttpUtil.sendReturnOKHttpRequest(url);
        try {
            JSONObject object = new JSONObject(response);
            return object.getString("total");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
